﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Jinjia.Approve.Common.Extensions
{
    /// <summary>
    /// 表达式扩展
    /// </summary>
    public static class ExpressionExtensions
    {
        public static MemberInfo GetMember<T>(this Expression<T> expr)
        {
            return expr.Body switch
            {
                MemberExpression memberExpression => memberExpression.Member,
                UnaryExpression { Operand: MemberExpression expression } =>
                    expression.Member,
                _ => default
            };
        }

        /// <summary>
        /// 动态拼接表达式And
        /// </summary>
        /// <param name="first">表达式1</param>
        /// <param name="second">表达式2</param>
        /// <returns>拼接后表达式</returns>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        /// <summary>
        /// 动态拼接表达式Or
        /// </summary>
        /// <param name="first">表达式1</param>
        /// <param name="second">表达式2</param>
        /// <returns>拼接后表达式</returns>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }

        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            var map = first.Parameters
                .Select((f, i) => new { f, s = second.Parameters[i] })
                .ToDictionary(p => p.s, p => p.f);
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }

        public static Expression ReplaceParameter(this Expression expression, ParameterExpression sourceParameter, ParameterExpression targetParameter)
        {
            return new ParameterReplacer { SourceParameter = sourceParameter, TargetParameter = targetParameter }.Visit(expression);
        }

    }

    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> _map;

        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            _map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }

        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression expression)
        {
            return new ParameterRebinder(map).Visit(expression);
        }

        protected override Expression VisitParameter(ParameterExpression parameterExpression)
        {
            if (_map.TryGetValue(parameterExpression, out var replacement))
            {
                parameterExpression = replacement;
            }

            return base.VisitParameter(parameterExpression);
        }
    }

    public class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression SourceParameter { get; set; }
        public ParameterExpression TargetParameter { get; set; }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (node == SourceParameter)
                return TargetParameter;

            return base.VisitParameter(node);
        }
    }
}